package edu.pw.p2pclient.data;

import java.util.Collection;
import java.util.LinkedHashSet;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import edu.pw.p2pclient.R;
import edu.pw.p2pclient.logic.DownloadManager;
import edu.pw.p2pclient.utils.ApplicationContext;

public class AvailableAdapter extends ArrayAdapter<Resource> {

	private LinkedHashSet<Resource> mResources = null;
	private ViewHolder mViewHolder = null;
	private FragmentActivity mParentActivity = null;

	public AvailableAdapter() {
		super(ApplicationContext.get(), R.layout.available_row);
		mResources = new LinkedHashSet<Resource>();
	}

	public void setParentActivity(FragmentActivity availableFragment) {
		mParentActivity = availableFragment;
	}

	private class ViewHolder {
		TextView fileName;
		TextView fileSize;
		// ImageView fileType;
		ImageView addDownload;
	}

	public void addAllAvailable(Collection<Resource> collection) {

		for (Resource resource : collection) {
			if (resource.isWifiShared() || resource.isBtShared()) {
				if (DownloadManager.getInstance().getDownloadAdapter()
						.contains(resource))
					resource.setIsBeingDownloaded(true);
				add(resource);
			}
		}
	}

	@Override
	public void add(Resource object) {

		boolean found = false;
		for (Resource res : mResources) {
			if (res.equals(object)) {
				found = true;
				if (object.isBtShared())
					res.increaseBtShared();
				if (object.isWifiShared())
					res.increaseWifiShared();
				return;
			}
		}
		if (!found) {
			mResources.add(object);
			// super.add(object);
		}
	}

	@Override
	public void clear() {

		mResources.clear();
		// super.clear();
	}

	public void resourcesDeletedFromQueue() {
		for (int i = 0; i < getCount(); ++i)
			getItem(i).setIsBeingDownloaded(
					DownloadManager.getInstance().getDownloadAdapter()
							.contains(getItem(i)));
	}

	@Override
	public int getCount() {

		return mResources.size();
		// return super.getCount();
	}

	@Override
	public Resource getItem(int position) {

		int i = 0;
		for (Resource resource : mResources) {
			if (position == i++)
				return resource;
		}
		return null;
	}

	public LinkedHashSet<Resource> getResources() {
		return mResources;
	}

	@Override
	public int getPosition(Resource item) {

		Resource[] res = mResources.toArray(new Resource[0]);
		for (int i = 0; i < mResources.size(); ++i) {
			if (res[i] == item)
				return i;
		}
		return -1;
	}

	@Override
	public void remove(Resource object) {

		for (Resource res : mResources) {
			if (res.equals(object)) {
				if (object.isBtShared())
					res.decreaseBtShared();
				if (object.isWifiShared())
					res.decreaseWifiShared();
				if (!res.isBtShared() && !res.isWifiShared())
					mResources.remove(res);
				return;
			}
		}
		// super.remove(object);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		if (convertView == null) {
			LayoutInflater inflater = (LayoutInflater) getContext()
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inflater.inflate(R.layout.available_row, parent,
					false);

			mViewHolder = new ViewHolder();

			mViewHolder.fileName = (TextView) convertView
					.findViewById(R.id.availableFilenameTextView);
			mViewHolder.fileSize = (TextView) convertView
					.findViewById(R.id.availableSizeTextView);
			// mViewHolder.fileType = (ImageView)
			// convertView.findViewById(R.id.availableImageView);
			mViewHolder.addDownload = (ImageView) convertView
					.findViewById(R.id.addAvailableImageView);

			convertView.setTag(mViewHolder);
		} else {
			mViewHolder = (ViewHolder) convertView.getTag();
		}
		final Resource resource = getItem(position);

		mViewHolder.fileName.setText(resource.getName());
		mViewHolder.fileSize.setText(String.valueOf(resource.getSize()));
		if (resource.isBeingDownloaded()) {
			mViewHolder.addDownload.setVisibility(View.INVISIBLE);
			mViewHolder.addDownload.setOnClickListener(null);
		} else {
			mViewHolder.addDownload.setVisibility(View.VISIBLE);
			mViewHolder.addDownload.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (resource.getSharingInfo().isPasswordProtected()) {
						AlertDialog.Builder alert = new AlertDialog.Builder(
								mParentActivity);

						alert.setTitle(R.string.enter_password);
						alert.setMessage(R.string.enter_password_full);

						final EditText input = new EditText(ApplicationContext
								.get());
						alert.setView(input)
								.setPositiveButton(android.R.string.ok,
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int whichButton) {
												if (input.getText().toString()
														.equals("")) {
													Toast.makeText(
															getContext(),
															R.string.you_must_enter_password,
															Toast.LENGTH_SHORT)
															.show();
													return;
												}
												resource.getSharingInfo()
														.setPassword(
																input.getText()
																		.toString());
												scheduleDownload(resource);
											}
										})
								.setNegativeButton(R.string.cancel,
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int whichButton) {
												input.setText("");
											}
										});

						alert.show();
					} else
						scheduleDownload(resource);
				}
			});
		}

		return convertView;
	}

	private void scheduleDownload(Resource resource) {
		DownloadManager.getInstance().scheduleDownload(
				new DownloadNode(resource));
		resource.setIsBeingDownloaded(true);
		notifyDataSetChanged();
		Toast.makeText(getContext(), R.string.resource_added_to_download_queue,
				Toast.LENGTH_SHORT).show();
	}
}
